package com.xck.clouddisk.exception;

import com.xck.clouddisk.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 这是粗略的异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e){
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error();
    }

    /**
     * 常见的异常处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ArithmeticException.class)
    public Result handleArithmeticException(ArithmeticException  e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error().message("算数异常");
    }

    @ResponseBody
    @ExceptionHandler(value = NullPointerException.class)
    public Result handleArithmeticException(NullPointerException  e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error().message("空指针异常");
    }

    @ResponseBody
    @ExceptionHandler(value = ArrayIndexOutOfBoundsException.class)
    public Result handleArithmeticException(ArrayIndexOutOfBoundsException  e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error().message("数组越界");
    }
    /**
     * @return 通过id查询一个用户  user是空的    业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result error(BusinessException e){
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error().message(e.getMsg()).code(e.getCode());
    }


}
